﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using MediatR;
namespace Casamiel.Application.Commands
{
    /// <summary>
    /// Preview invoice command handler.
    /// </summary>
    public sealed class PreviewInvoiceCommandHandler:IRequestHandler<PreviewInvoiceCommand,BaseResult<PreviewInvoiceRsp>>
    {
       // private readonly NLog.ILogger _logger = NLog.LogManager.GetLogger("BizInfo");
        private readonly IInvoiceDetailRepository _detailRepository;

        public PreviewInvoiceCommandHandler(IInvoiceDetailRepository invoiceDetailRepository)
        {
            _detailRepository = invoiceDetailRepository;
        }

        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<BaseResult<PreviewInvoiceRsp>> Handle(PreviewInvoiceCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var list = await _detailRepository.GetListAsync<ICasaMielSession>(request.IDS,request.Mobile).ConfigureAwait(false);
            if (!list.Any())
            {
                return new BaseResult<PreviewInvoiceRsp>(null, 9999, "没有可开的记录");
            }
            var ordertotal = list.Sum(c => c.Amount);
            if (ordertotal > 9999)
            {
                return new BaseResult<PreviewInvoiceRsp>(null, 9999, "单张开票金额不能超过9999");
            }

            return new BaseResult<PreviewInvoiceRsp>(new PreviewInvoiceRsp { TotalAmount = ordertotal, Ids = request.IDS },0, "");
        }
    }
}
